package com.alphathink.BitMapUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.widget.ImageView;

public class BitmapLoadTask extends AsyncTask<Void, Void, Bitmap> {

	private WeakReference<ImageView> reference = null;

	private String data = "";
	private int width = 0;
	private int height = 0;

	/**
	 * 适用于目标控件的大小无法确定的情况<br>
	 * <b>eg:</b>在activity的oncreate方法中，一般情况下控件的大小是无法确定的。也就是说无法通过get狂高获取精确的值。
	 * 
	 * @param url
	 * @param imageview
	 * @param targetWidth
	 *            目标宽度
	 * @param targetHeight
	 *            目标高度
	 */
	public BitmapLoadTask(String url, ImageView imageview, int targetWidth,
			int targetHeight) {
		super();
		this.data = url;

		reference = new WeakReference<ImageView>(imageview);
		width = targetWidth;
		height = targetHeight;
	}

	/**
	 * 相较于{@link BitmapLoadTask(String url, ImageView imageview, int
	 * targetWidth, int targetHeight))}，此时的控件大小是可以确定的。根据imageview参数确定。
	 * 
	 * @param url
	 * @param imageview
	 */
	public BitmapLoadTask(String url, ImageView imageview) {
		super();
		this.data = url;
		reference = new WeakReference<ImageView>(imageview);
		width = imageview.getWidth();
		height = imageview.getHeight();
	}

	@Override
	protected Bitmap doInBackground(Void... params) {

		System.out.println("data:  " + data);
		System.out.println("BitmapLoadTask-->doInBackground-->width:" + width
				+ ",height" + height);
		// String imagename = ImageURLUtil.getName(data);
		Bitmap bitmap = null;
		BitmapLruCache lruCache = BitmapLruCache.getInstance();
		// 检查是否有diskcache，如果有则解析内容，并且加入缓存.并且返回
		BitmapDiskCache bitmapDiskCache = BitmapDiskCache.getInstance();
		File file = bitmapDiskCache.getCache(data.hashCode() + "");
		if (file != null) {
			bitmap = DecodeBitmap.decodeBtimapFromFile(
					BitmapDiskCache.CACHE_DIR + File.separator
							+ data.hashCode() + "", width, height);
			if (bitmap != null) {
				lruCache.put(data.hashCode() + "", bitmap);
			}
			System.out
					.println("BitmapLoadTask-->doInBackground-->DiskCache hit!!");
			return bitmap;
		}
		// 准备从网络下载图片下载图片
		// 加入memorycache
		// 加入diskcache
		// HttpURLConnection conn = null;
		InputStream inputStream = null;
		try {
			HttpClient httpClient = HttpClientSingle
					.getHttpClient(HttpClientSingle.BINARY);
			System.out.println("data:" + data);
			HttpGet get = new HttpGet(data);
			HttpResponse response = httpClient.execute(get);
			// ;
			System.out.println("bitmapLoadPIC："
					+ response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == 200) {
				System.out.println("图片下载成功 啦啦啦 哈哈哈哈哈哈");
				inputStream = response.getEntity().getContent();
				// 下载成功并添加进diskCache
				bitmap = DecodeBitmap.decodeBtimapFromStream(inputStream,
						data.hashCode() + "", width, height);
				// 添加进memorycache
				System.out
						.println("BitmapLoadTask-->doInBackground-->imagename:"
								+ data.hashCode() + "");
				if (bitmap != null) {
					lruCache.put(data.hashCode() + "", bitmap);
				}
				inputStream.close();
			}
			// URL connUrl = new URL(data);
			// conn = (HttpURLConnection) connUrl.openConnection();
			// conn.setConnectTimeout(15000);
			// conn.setReadTimeout(10000);
			// conn.connect();
			// int rescode = conn.getResponseCode();
			// if (rescode == HttpURLConnection.HTTP_OK) {
			// inputStream = conn.getInputStream();
			// // 下载成功并添加进diskCache
			// bitmap = DecodeBitmap.decodeBtimapFromStream(inputStream,
			// imagename, width, height);
			// // 添加进memorycache
			// System.out
			// .println("BitmapLoadTask-->doInBackground-->imagename:"
			// + imagename);
			// if (bitmap != null) {
			// lruCache.put(imagename, bitmap);
			// }
			// }
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// // 如果链接不为空关闭连接
			// if (conn != null) {
			// conn.disconnect();
			// }
		}
		// 如果无缓存且下载失败bitmap为null.
		return bitmap;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		if (isCancelled()) {
			System.out
					.println("BiamapLoadTask-->onPostExecute-->iscancelled����");
			return;
		}
		if (reference != null) {
			ImageView imageView = reference.get();
			BitmapLoadTask loadTask = BitmapUtil.getBitmapWorkerTask(imageView);
			// 若果引用还在
			if (imageView != null) {
				// 如果返回结果不为空
				if (result != null) {
					if (this == loadTask) {
						imageView.setImageBitmap(result);
					}
				} else {
					// 如果返回结果为空
					System.out
							.println("BiamapLoadTask-->onPostExecute-->这里设置加载失败的图片！！");
				}
			}
		}
		super.onPostExecute(result);
	}

	public String getData() {
		return data;
	}
}
